package com.smat.taglib;

import com.smat.taglib.html.Div;
import com.smat.taglib.html.Element;
import com.smat.taglib.html.Img;
import com.smat.taglib.html.Li;
import com.smat.taglib.html.Span;
import com.smat.taglib.html.Text;
import com.smat.taglib.html.Ul;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.jsp.JspException;

public abstract class BaseItemTag extends BaseTag
{
  protected List<Map<String, Object>> items;

  protected abstract String getText();

  protected abstract String getSpriteCssClass();

  protected abstract String getImageUrl();

  protected abstract boolean getExpanded();

  protected abstract boolean getEnabled();

  public void initialize()
  {
    this.items = new ArrayList();
    super.initialize();
  }

  public void destroy()
  {
    this.items = null;
    super.destroy();
  }

  protected void renderContents(Element<?> element) {
    String spriteCssClass = getSpriteCssClass();

    if ((spriteCssClass != null) && (spriteCssClass.trim().length() > 0)) {
      Span sprite = new Span();
      sprite.attr("class", "k-sprite " + spriteCssClass);
      element.append(sprite);
    }

    String imageUrl = getImageUrl();

    if ((imageUrl != null) && (imageUrl.trim().length() > 0)) {
      Img image = new Img();
      image.attr("class", "k-image");
      image.attr("alt", "");
      image.attr("src", imageUrl);
      element.append(image);
    }

    element.append(new Text(getText()));

    String html = body();

    if (!html.isEmpty())
      appendContent(element, html);
  }

  public void addAttributes(Li element)
  {
    if ((isSet("expanded")) && (getExpanded())) {
      element.attr("data-expanded", "true");
    }

    if ((isSet("enabled")) && (!getEnabled()))
      element.attr("disabled", "disabled");
  }

  public int doEndTag()
    throws JspException
  {
    Li element = new Li();

    addAttributes(element);

    renderContents(element);
    try
    {
      element.write(this.pageContext.getOut());
    } catch (IOException exception) {
      throw new JspException(exception);
    }

    return super.doEndTag();
  }

  protected void appendContent(Element<?> element, String html)
  {
    Element contentElement;
    if (this.items.size() > 0)
      contentElement = new Ul();
    else {
      contentElement = new Div();
    }

    contentElement.html(html);

    element.append(contentElement);
  }
}